package cn.harperDog.multithreading;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author hua
 * @description
 * @date 2022/3/6
 * <p>
 * 多个线程轮流打印出ABC
 */
public class MTPrintABC {
    Lock lock = new ReentrantLock();
    Condition ca = lock.newCondition();
    Condition cb = lock.newCondition();
    Condition cc = lock.newCondition();

    //信号量
    private volatile int value = 0;

    //打印多少遍
    private int count = 10;

    public void printABC() {
        new A().start();
        new B().start();
        new C().start();
    }

    public static void main(String[] args) {
        MTPrintABC mtPrintABC = new MTPrintABC();
        mtPrintABC.printABC();
    }

    class A extends Thread {
        @Override
        public void run() {
            lock.lock();
            try {
                for (int i = 0; i < count; i++) {
                    if (value % 3 != 0) {
                        ca.await();
                    }
                    System.out.print("A ");
                    value++;
                    cb.signal();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    class B extends Thread {
        @Override
        public void run() {
            lock.lock();
            try {
                for (int i = 0; i < count; i++) {
                    if (value % 3 != 1) {
                        cb.await();
                    }
                    System.out.print("B ");
                    value++;
                    cc.signal();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    class C extends Thread {
        @Override
        public void run() {
            lock.lock();
            try {
                for (int i = 0; i < count; i++) {
                    if (value % 3 != 2) {
                        cc.await();
                    }
                    System.out.print("C ");
                    value++;
                    ca.signal();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}


